package com.nd.demo.util;

import com.nd.demo.bean.IssueBean;

import java.util.*;

public class MatchingUtil {


    /**
     * 从集合中随机返回一个匹配度最高的问题元素
     * @param issueBeanList
     * @param issue
     * @return
     */
    public static IssueBean findReplay(List<IssueBean> issueBeanList,String issue){
        Map<String,Integer> tempMap = new HashMap<>();
        IssueBean resIssueBean = new IssueBean();
        for(IssueBean issueBean : issueBeanList){
            Integer matDeg = matchIssue(issueBean.getIssueName(),issue);
            tempMap.put(issueBean.getIssueName()+","+issueBean.getId(),matDeg);
        }
        List<String> maxMathKeys = getMaxValue(tempMap);
        //随机选一种答案
        Random random = new Random();
        int index = random.nextInt(maxMathKeys.size());
        String[] temp = maxMathKeys.get(index).split(",");
        resIssueBean.setId(temp[1]);
        resIssueBean.setIssueName(temp[0]);
//        System.out.println("找到的问题为："+resIssueBean.getIssueName());//000000000000000000000000
//        for(String key : tempMap.keySet()){//00000000000000000000000000000000
//            Integer value = tempMap.get(key);
//            System.out.println(key+":"+value);
//        }
        return resIssueBean;
    }


    /**
     * 获取map中最大的值对应的键的数据集合
     * @param map
     * @return
     */
    private static List<String> getMaxValue(Map<String, Integer> map) {
        List<String > res = new ArrayList<>();
        if (map == null)
            return null;
        int length =map.size();
        Collection<Integer> c = map.values();
        Object[] obj = c.toArray();
        Arrays.sort(obj);
        for(String key:map.keySet()){
            if(map.get(key).equals(obj[length-1])){
                res.add(key);
            }
        }
        return res;
    }

    /**
     * 获取问题的匹配度,即issue的与issue2的最长公共字串
     * @param issue
     * @param issue2
     * @return
     */
    private static int matchIssue(String issue,String issue2){
        int[][] record = new int[issue.length()][issue2.length()];
        int maxLen = 0;
        for(int i=0; i<issue.length(); ++i)
        for (int j = 0; j < issue2.length(); ++j) {
            if (issue.charAt(i) == issue2.charAt(j)) {
//                System.out.println(issue.charAt(i)+"@@@"+issue2.charAt(j));
                if (i == 0 || j == 0) {
                    record[i][j] = 1;
                }
                else {
                    record[i][j] = record[i - 1][j - 1] + 1;
                }
            }
            else {
                record[i][j] = 0;
            }

            if (record[i][j] > maxLen) {
                maxLen = record[i][j];
            }
        }
        return maxLen;
        }
}
